package home.my.base.web;

import home.my.base.model.BaseObj;
import home.my.base.service.BaseService;
import home.my.base.sql.AbsCondition;
import home.my.base.sql.ConditionQuery;
import home.my.base.sql.ConditionQueryHunder;
import home.my.base.util.downloader.CsvDownLoader;
import home.my.base.util.downloader.DownLoader;
import home.my.recordmanage.util.GlobalParameters;

import java.io.IOException;
import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;
import java.util.List;

import javax.servlet.http.HttpServletResponse;

import org.apache.struts2.json.annotations.JSON;

import com.opensymphony.xwork2.Action;

public abstract class SearchAction<T extends BaseObj, S extends BaseService<T>>
		extends BaseAction implements GlobalParameters {
    public String orders;
    public S service;
    public List<T> pojoList;
    private DownLoader<T> downloader;
    
    public String list(){
    	pojoList = service.find(buildQuery(),false);
    	return Action.SUCCESS;
    }
    
    public void exportCsv(){
		HttpServletResponse res = super.getResponse();
		res.setContentType("text/csv;charset=GBK");
		res.setHeader("Content-Disposition", "attachment;filename=export.csv");
		DownLoader<T> downLoader = this.getDownloader();
		if(downLoader!=null && downLoader instanceof CsvDownLoader){
			try {
				CsvDownLoader<T> csvDownLoader = (CsvDownLoader<T>)downLoader;
				HttpServletResponse response = super.getResponse();
				response.getWriter().println(csvDownLoader.buildTitle());
				service.export(this.buildQuery(),csvDownLoader);
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
    }
    
    public ConditionQuery buildQuery(){
    	Type[] types = ((ParameterizedType) getClass().getGenericSuperclass()).getActualTypeArguments();
    	@SuppressWarnings("rawtypes")
    	String pojoName = ((Class) types[0]).getName();
    	ConditionQuery q = new ConditionQuery(pojoName);
    	q.setOrders(orders);
    	List<AbsCondition> conditionList = ConditionQueryHunder.buildConditionList(this);
    	q.setConditionList(conditionList);
    	return q;
    }
    
	public String getOrders() {
		return orders;
	}
	public void setOrders(String orders) {
		this.orders = orders;
	}
	
	@JSON(serialize=false)
	public S getService() {
		return service;
	}
	public void setService(S service) {
		this.service = service;
	}
	
	public List<T> getPojoList() {
		return pojoList;
	}
	public void setPojoList(List<T> pojoList) {
		this.pojoList = pojoList;
	}
	
	public DownLoader<T> getDownloader() {
		return downloader;
	}
	public void setDownloader(DownLoader<T> downloader) {
		this.downloader = downloader;
	}
	
}
